package cn.zzmx.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 安全认证
 */
@Configuration
public class BrowerSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()          // 定义当需要用户登录时候，转到的登录页面。
                .loginPage("/login.html")      // 设置登录页面
                .loginProcessingUrl("/login") //自定义的登录接口
                .successForwardUrl("/user/loginSuccess")
                .failureForwardUrl("/user/loginFailure")
                .usernameParameter("username")
                .passwordParameter("password")
                .and()

              .authorizeRequests()    // 定义哪些URL需要被保护、哪些不需要被保护
                .antMatchers("/css/**", "/js/**","/images/**", "/webjars/**", "**/favicon.ico", "/login.html","/error.html")
                .permitAll()   // 设置所有人都可以访问登录页面
                .anyRequest()       // 任何请求,登录后可以访问
                .hasAnyRole("VIP","SVIP","ADMIN","USER")//拥有其中一种角色才能访问
//                .authenticated()
                .and()


              .headers().disable()
                .csrf().disable();     // 关闭csrf防护
    }

    /**
     * 密码加密 BCryptPasswordEncoder
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}